/***************************************************************************
[FileName]
-------------------
    begin                : 03.201s1
    copyright            : by kuzkok
    email                : kuzkok@gmail.com

***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*   
*   Данная программа является свободным программным обеспечением;         *
*   Вы можете распространять ее и/или модифицировать в соответствии с     *
*   GNU General Public License опубликованной Фондом свободного           *
*   программного обеспечения; используемая версия лицензии - 2 или        *
*   (по вашему выбору) любая более поздняя                                *
***************************************************************************/
#include <QMessageBox>

//#include "qgsdatasourceuri.h"

#include "listwidget.h"
#include "ui_listwidget.h"
#include "dbconnection.h"
#include "psqlenumdelegate.h"
#include "tunetablemodel.h"
//#include "unique.h"

ListWidget::ListWidget(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::ListWidget)
{
    ui->setupUi(this);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->pushButtonFilterData->setEnabled(false);
    connect(ui->pushButtonZoomToSelected, SIGNAL(clicked()), this, SLOT(zoomToSelected()));
    connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(showCard(QModelIndex)));
    connect(ui->pushButtonSaveEdit, SIGNAL(clicked()), this, SLOT(saveChanges()));    
    connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
    connect(ui->pushButtonStartStopEditActivity, SIGNAL(clicked()), this, SLOT(changeEditMode()));
    connect(ui->pushButtonAddRow, SIGNAL(clicked()), this, SLOT(addRow()));
    connect(ui->pushButtonDeleteRow, SIGNAL(clicked()), this, SLOT(removeSelected()));
}

ListWidget::~ListWidget()
{
    delete ui;
    delete tableModel;
}

void ListWidget::selectionChanged(QItemSelection select, QItemSelection deselect)
{ 
    ui->labelSelectedCount->setText(QString("%1 из %2").arg(ui->tableView->selectionModel()->selectedRows().count()).arg(tableModel->rowCount()));
}

void ListWidget::temslot()
{
    //QMessageBox::information(0, "", "row changed");
}

void ListWidget::loadData(QString theTableName, QString where_clause)
{
    //mapCanvas =  unique::inst()->QgisIface()->mapCanvas();
    tableName = theTableName;    
    if (dbconnection::instance()->connected())
    {
        tableModel = new CustomRelationModel(this, dbconnection::instance()->database());
        tableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
        tableModel->setTable(theTableName);
        tableModel->setFilter(where_clause);
        if(tableModel->select())
        {
            isDirty = false;
            ui->pushButtonAddRow->setEnabled(false);
            ui->pushButtonDeleteRow->setEnabled(false);
            ui->pushButtonSaveEdit->setEnabled(false);
            psqlenumdelegate *delegate = new psqlenumdelegate(theTableName, dbconnection::instance()->database());
            ui->tableView->setModel(tableModel);
            ui->tableView->setItemDelegate(delegate);
            connect(tableModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(dataChanged()));
            connect(ui->tableView->selectionModel(),
                    SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
                    this,
                    SLOT(selectionChanged(QItemSelection,QItemSelection)));
            tunetablemodel::tune(tableModel, ui->tableView);
        }
        else
            QMessageBox::information(this, "error", tableModel->lastError().text());   
    }
}

void ListWidget::zoomToSelected()
{
//    if(layer)
//        mapCanvas->zoomToSelected(layer);
}

void ListWidget::invertSelection()
{

}

void ListWidget::showCard(QModelIndex idx)
{
    int fldFID = tableModel->record().indexOf("feature_id");
    QString fid = tableModel->data(tableModel->index(idx.row(), fldFID)).toString();
    QString tName = tableName.remove('"').toLower();
    if(tName == "выделы")
    {

    }

}

void ListWidget::saveChanges()
{
    if(tableModel->submitAll())
    {
        isDirty = false;
        ui->labelFDeclaration->setText("Сохранено");
    }
    else
        QMessageBox::information(this, "Ошибка", tableModel->lastError().text());
}

void ListWidget::changeEditMode()
{
    if(ui->pushButtonStartStopEditActivity->isChecked())
    {
        ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked |
                                       QAbstractItemView::EditKeyPressed |
                                       QAbstractItemView::AnyKeyPressed);
        ui->pushButtonAddRow->setEnabled(true);
        ui->pushButtonDeleteRow->setEnabled(true);
        ui->pushButtonSaveEdit->setEnabled(true);
        ui->tableView->setSortingEnabled(false);
    }
    else
    {
        if(isDirty)
        {
            switch(QMessageBox::information(this, "Информация", "Сохранить изменения",
                                        QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel ))
            {
            case QMessageBox::Yes:
                tableModel->submitAll();
                break;
            case QMessageBox::No:
                tableModel->revertAll();
                break;
            case QMessageBox::Cancel:
                ui->pushButtonStartStopEditActivity->setChecked(true);
                return;
                break;
            default:
                break;
            }
        }
        ui->pushButtonAddRow->setEnabled(false);
        ui->pushButtonDeleteRow->setEnabled(false);
        ui->pushButtonSaveEdit->setEnabled(false);
        ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);        
        ui->tableView->setSortingEnabled(true);
    }
}

void ListWidget::removeSelected()
{
    if(QMessageBox::question(this, "Удаление", "Удалить выделенные строки?", QMessageBox::Yes|QMessageBox::No) ==
       QMessageBox::Yes)
        foreach(QModelIndex idx, ui->tableView->selectionModel()->selectedRows())
                tableModel->removeRow(idx.row());
}
